/*
 * ******************************************************
 *   Copyright ©, 2017-2019, 安徽财金信息科技有限公司
 * ******************************************************
 */
package com.wy.poties.common.intercepter;

import com.wy.poties.common.model.MainContext;
import com.wy.poties.common.model.ReqInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>Description:</p>
 *
 *
 * @author
 * @version 1.0
 * @date 2020/06/04 16:01
 */
@Slf4j
@Component
public class CommonInterceptor implements HandlerInterceptor {

    /**
     * 请求来源字段key
     */
    private static final String COMMON_KEY_SOURCE = "source";

    /**
     * App版本字段key
     */
    private static final String COMMON_KEY_VERSION = "version";

    /**
     * App操作系统版本字段key
     */
    private static final String COMMON_KEY_OS = "os";

    /**
     * 客户端机型字段key
     */
    private static final String COMMON_KEY_MODEL = "model";

    /**
     * 设备唯一标识
     */
    private static final String COMMON_KEY_DEVICE_ID = "deviceId";

    /**
     * IP字段key
     */
    private static final String COMMON_KEY_IP = "ip";

    /**
     * 页面名称字段key
     */
    private static final String COMMON_KEY_PAGE_NAME = "pageName";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 请求来源：1-Android；2-iOS
        String source = request.getHeader(COMMON_KEY_SOURCE);
        Integer appType = StringUtils.isEmpty(source) ? 0 : Integer.valueOf(source);
        // 版本号，如：0.0.1，1.2.12
        String version = request.getHeader(COMMON_KEY_VERSION);
        // 操作系统，包括版本号
        String os = request.getHeader(COMMON_KEY_OS);
        // 机型，如iPhone X
        String model = request.getHeader(COMMON_KEY_MODEL);
        // 设备唯一标识
        String deviceId = request.getHeader(COMMON_KEY_DEVICE_ID);
        // ip地址，如：185.99.0.12
        String ip = request.getHeader(COMMON_KEY_IP);
        // 页面名称，从请求参数（非header）中取
        String pageName = request.getParameter(COMMON_KEY_PAGE_NAME);

        ReqInfo reqInfo = new ReqInfo();
        reqInfo.setAppType(appType);
        reqInfo.setVersion(version);
        reqInfo.setOs(os);
        reqInfo.setModel(model);
        reqInfo.setDeviceId(deviceId);
        reqInfo.setIp(ip);
        reqInfo.setPageName(pageName);

        MainContext.setReqContext(reqInfo);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求执行完成之后需要将变量清空
        MainContext.clearReqContext();
    }

}
